{% extends "base.html" %}

{% block page_title %}AI平台管理{% endblock %}

{% block extra_css %}
    <style>
        /* 主题颜色变量 - 更优雅的配色方案 */
        :root {
            --primary-color: #3a86ff;
            --primary-light: #60a5fa;
            --primary-dark: #2563eb;
            --secondary-color: #38bdf8;
            --accent-color: #8b5cf6;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
            --neutral-50: #f9fafb;
            --neutral-100: #f3f4f6;
            --neutral-200: #e5e7eb;
            --neutral-300: #d1d5db;
            --neutral-800: #1f2937;
            --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            --card-shadow-hover: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            --plugin-card-bg: #f8f9fa;
            --plugin-header-bg: #f0f2f5;
        }

        /* 页面容器样式 */
        .ai-platforms-container {
            max-width: 1400px;
            margin: 0 auto;
        }

        /* 平台卡片样式 - 完全参考插件管理界面 */
        .platform-card {
            border-radius: 8px;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
            border: 1px solid rgba(0,0,0,0.1);
            overflow: hidden;
            background-color: white;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .platform-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }

        /* 平台卡片头部 - 完全参考插件管理界面 */
        .platform-header {
            padding: 12px 15px;
            border-radius: 8px 8px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: var(--plugin-header-bg);
            position: relative;
            overflow: visible;
            color: var(--neutral-800);
        }
        /* 平台头部装饰元素 */
        .platform-header::before {
            content: '';
            position: absolute;
            top: -20px;
            right: -20px;
            width: 120px;
            height: 120px;
            background-color: rgba(0, 0, 0, 0.03);
            border-radius: 50%;
            z-index: 0;
            pointer-events: none; /* 确保装饰元素不会阻止点击 */
        }

        /* 状态容器样式 */
        .plugin-status-container {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            align-items: center;
            z-index: 10;
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 15px;
            padding: 1px 3px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }

        .status-badge {
            font-size: 0.65rem;
            padding: 0.2em 0.5em;
            font-weight: 500;
            border-radius: 15px;
            vertical-align: middle;
            display: inline-block;
            min-width: 50px;
            text-align: center;
        }

        /* 开关按钮样式 - 参考插件管理界面 */
        .form-check-input {
            position: relative;
            z-index: 10; /* 确保开关按钮始终在最上层 */
            cursor: pointer;
            width: 2.2rem; /* 减小宽度 */
            height: 1.2rem; /* 减小高度 */
            border: 1px solid rgba(255, 255, 255, 0.3);
            background-color: rgba(255, 255, 255, 0.2) !important;
            background-image: none !important;
            border-radius: 0.6rem; /* 确保圆形效果 */
        }

        /* 开关按钮选中状态 */
        .form-check-input:checked {
            background-color: #10b981 !important; /* 使用绿色 */
            border-color: #10b981 !important;
        }

        /* 自定义开关按钮的圆圈样式 */
        .form-check-input:before {
            content: '';
            position: absolute;
            top: 1px;
            left: 1px;
            width: calc(50% - 2px);
            height: calc(100% - 2px);
            background-color: white;
            border-radius: 50%;
            transition: transform 0.2s ease;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
            transform: translateX(0);
        }

        .form-check-input:checked:before {
            transform: translateX(100%);
            left: calc(50% - 1px);
        }

        .form-check {
            position: relative;
            z-index: 10;
            margin-right: 5px;
        }

        /* 平台图标 - 参考插件管理界面 */
        .platform-icon-container {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: linear-gradient(135deg, #3a86ff, #2563eb);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            flex-shrink: 0;
            box-shadow: 0 3px 6px rgba(0,0,0,0.1);
        }

        .platform-icon {
            font-size: 1.4rem;
            color: white;
        }

        /* 平台标题 - 减小大小 */
        .platform-title {
            margin: 0;
            font-size: 1.1rem; /* 减小标题大小 */
            font-weight: 600;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            position: relative;
            z-index: 1;
        }

        /* 平台卡片主体 */
        .platform-body {
            padding: 20px;
            background-color: white;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        /* 平台描述 */
        .platform-description {
            margin-top: 0;
            margin-bottom: 15px;
            color: var(--neutral-800);
            line-height: 1.5;
            flex-grow: 1;
        }

        /* 文本截断样式 */
        .text-truncate-2 {
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            max-height: 3em;
        }

        /* 平台状态标签 */
        .platform-status {
            display: inline-flex;
            align-items: center;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
            margin-top: 0;
        }

        .platform-status::before {
            font-family: "bootstrap-icons";
            margin-right: 6px;
        }

        .status-enabled {
            background-color: rgba(16, 185, 129, 0.15);
            color: #065f46;
            border: 1px solid rgba(16, 185, 129, 0.4);
            font-weight: 600;
        }

        .status-enabled::before {
            content: "\F26B";
            color: var(--success-color);
            font-size: 1.1rem;
        }

        .status-disabled {
            background-color: rgba(239, 68, 68, 0.15);
            color: #991b1b;
            border: 1px solid rgba(239, 68, 68, 0.4);
            font-weight: 600;
        }

        .status-disabled::before {
            content: "\F623";
            color: var(--danger-color);
            font-size: 1.1rem;
        }
        .form-group {
            margin-bottom: 18px;
        }

        /* 模态框样式 */
        .modal-header {
            border-radius: 12px 12px 0 0;
            color: white;
            background-image: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            padding: 15px 20px;
        }

        /* 确保模态框居中且大小合适 */
        .modal-dialog {
            max-width: 80%;
            margin: 1.75rem auto;
        }

        /* 确保模态框在显示时居中 */
        .modal.show {
            display: flex !important;
            align-items: center;
            justify-content: center;
        }

        .modal-title {
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .modal-title::before {
            content: "\F3D7";
            font-family: "bootstrap-icons";
            margin-right: 10px;
            font-size: 1.2rem;
        }

        .modal-content {
            border: none;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid var(--neutral-200);
        }

        /* 测试结果样式 */
        .test-result {
            padding: 12px 15px;
            border-radius: 12px;
            margin-top: 15px;
            position: relative;
            padding-left: 40px;
        }

        .test-result::before {
            font-family: "bootstrap-icons";
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 1.2rem;
        }

        .test-success {
            background-color: rgba(74, 222, 128, 0.15);
            color: #166534;
            border: 1px solid rgba(74, 222, 128, 0.3);
        }

        .test-success::before {
            content: "\F26B";
            color: var(--success-color);
        }

        .test-error {
            background-color: rgba(248, 113, 113, 0.15);
            color: #991b1b;
            border: 1px solid rgba(248, 113, 113, 0.3);
        }

        .test-error::before {
            content: "\F623";
            color: var(--danger-color);
        }

        /* 平台卡片底部 */
        .platform-footer {
            padding: 15px 20px;
            background-color: var(--neutral-50);
            border-top: 1px solid var(--neutral-200);
            display: flex;
            justify-content: flex-end;
        }

        /* 配置按钮 */
        .btn-config {
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            white-space: nowrap;
            border-radius: 20px;
            transition: all 0.2s ease;
        }

        .btn-config:hover {
            transform: translateY(-2px);
            box-shadow: 0 3px 8px rgba(0,0,0,0.1);
        }

        /* 配置编辑器 */
        #config-editor {
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
            font-size: 0.9rem;
            line-height: 1.5;
            padding: 12px;
            border-radius: 8px;
            border: 1px solid var(--neutral-300);
            min-height: 350px;
            resize: vertical;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="ai-platforms-container">
        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-4 border-bottom">
            <h1 class="h2">
                <i class="bi bi-robot me-2 text-primary"></i>AI平台管理
            </h1>
        </div>

        <div class="alert alert-info mb-4" role="alert">
            <div class="d-flex">
                <div class="me-3">
                    <i class="bi bi-info-circle-fill fs-4"></i>
                </div>
                <div>
                    <h5 class="alert-heading">平台管理说明</h5>
                    <p class="mb-0">在这里管理AI平台插件，选择一个平台后将自动启用相关插件并禁用其他AI平台插件。每次只能启用一个AI平台。</p>
                </div>
            </div>
        </div>

        <!-- AI插件卡片区域 -->
        <div class="row" id="ai-plugins-container">
            {% if ai_plugins %}
                {% for plugin in ai_plugins %}
                    <div class="col-md-6 col-lg-4 col-xl-3 mb-4">
                        <div class="platform-card" data-aos="fade-up" data-aos-delay="{{ loop.index * 50 }}">
                            <div class="platform-header">
                                <div class="plugin-status-container">
                                    <span class="badge {{ 'bg-success' if plugin.enabled else 'bg-secondary' }} status-badge">
                                        {{ '已启用' if plugin.enabled else '未启用' }}
                                    </span>
                                    <div class="form-check form-switch plugin-switch ms-2">
                                        <input class="form-check-input" type="checkbox" role="switch"
                                            id="plugin-{{ plugin.id }}"
                                            {% if plugin.enabled %}checked{% endif %}
                                            onclick="togglePlugin('{{ plugin.id }}', this.checked)">
                                        <label class="form-check-label visually-hidden" for="plugin-{{ plugin.id }}">
                                            切换{{ plugin.name }}状态
                                        </label>
                                    </div>
                                </div>
                                <div class="d-flex align-items-center">
                                    <div class="platform-icon-container">
                                        <i class="bi bi-robot platform-icon"></i>
                                    </div>
                                    <div class="ms-3">
                                        <h5 class="platform-title mb-0 fw-bold">{{ plugin.name }}</h5>
                                        <div class="text-muted small">v{{ plugin.version }}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="platform-body p-3 d-flex flex-column">
                                <p class="platform-description text-truncate-2" title="{{ plugin.description }}">{{ plugin.description }}</p>
                                <div class="mt-auto pt-3">
                                    <div class="text-muted small text-truncate mb-2" title="{{ plugin.author or '未知作者' }}">
                                        <i class="bi bi-person me-1"></i>{{ plugin.author or '未知作者' }}
                                    </div>
                                    <div class="d-flex flex-wrap gap-2 justify-content-start align-items-center">
                                        <button class="btn btn-sm btn-outline-primary rounded-pill btn-config" onclick="showConfig('{{ plugin.id }}')">
                                            <i class="bi bi-gear-fill me-1"></i>配置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                {% endfor %}
            {% else %}
                <div class="col-12 text-center py-5">
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i>
                        未找到AI平台插件。请先安装并标记AI平台插件。
                    </div>
                </div>
            {% endif %}
        </div>
    </div>
    <!-- 插件配置模态框 -->
    <div class="modal" id="plugin-config-modal" tabindex="-1" aria-labelledby="plugin-config-title" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="plugin-config-title"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <!-- 加载状态 -->
                    <div id="plugin-config-loading" class="text-center py-4" style="display: none;">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">正在加载配置...</p>
                    </div>

                    <!-- 错误提示 -->
                    <div id="plugin-config-error" class="alert alert-danger d-none" role="alert">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i>
                        <span></span>
                    </div>

                    <!-- 配置表单容器 -->
                    <div id="plugin-config-form"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-lg me-1"></i>关闭
                    </button>
                    <button type="button" class="btn btn-primary" id="plugin-config-save">
                        <i class="bi bi-save me-1"></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 当前选中的插件ID
        let currentPluginId = null;

        // 切换插件启用状态
        async function togglePlugin(pluginId, enabled) {
            try {
                // 显示加载中状态
                const loadingToast = document.createElement('div');
                loadingToast.className = 'toast align-items-center text-white bg-info border-0 position-fixed top-0 start-50 translate-middle-x mt-4';
                loadingToast.style.zIndex = '9999';
                loadingToast.setAttribute('role', 'alert');
                loadingToast.setAttribute('aria-live', 'assertive');
                loadingToast.setAttribute('aria-atomic', 'true');
                loadingToast.innerHTML = `
                    <div class="d-flex">
                        <div class="toast-body">
                            <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                            正在${enabled ? '启用' : '禁用'}插件...
                        </div>
                    </div>
                `;
                document.body.appendChild(loadingToast);
                const loadingToastInstance = new bootstrap.Toast(loadingToast);
                loadingToastInstance.show();

                if (!enabled) {
                    // 如果是禁用操作，直接执行
                    const response = await fetch(`/api/plugins/${pluginId}/disable`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    const data = await response.json();

                    if (data.success) {
                        loadingToastInstance.hide();
                        setTimeout(() => {
                            loadingToast.remove();
                            location.reload();
                        }, 150);
                    } else {
                        loadingToastInstance.hide();
                        setTimeout(() => loadingToast.remove(), 150);
                        document.getElementById(`plugin-${pluginId}`).checked = true;
                        showError('禁用插件失败: ' + (data.message || '未知错误'));
                    }
                } else {
                    // 如果是启用操作，首先禁用其他所有AI平台插件
                    // 获取所有已启用的AI平台插件
                    const enabledPlugins = [];
                    document.querySelectorAll('.form-check-input:checked').forEach(checkbox => {
                        if (checkbox.id !== `plugin-${pluginId}`) {
                            enabledPlugins.push(checkbox.id.replace('plugin-', ''));
                        }
                    });

                    // 禁用其他已启用的AI平台插件
                    for (const otherPluginId of enabledPlugins) {
                        try {
                            await fetch(`/api/plugins/${otherPluginId}/disable`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            });
                        } catch (error) {
                            console.error(`禁用插件 ${otherPluginId} 失败:`, error);
                        }
                    }

                    // 启用当前插件
                    const response = await fetch(`/api/plugins/${pluginId}/enable`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    const data = await response.json();

                    if (data.success) {
                        loadingToastInstance.hide();
                        setTimeout(() => {
                            loadingToast.remove();
                            location.reload();
                        }, 150);
                    } else {
                        loadingToastInstance.hide();
                        setTimeout(() => loadingToast.remove(), 150);
                        document.getElementById(`plugin-${pluginId}`).checked = false;
                        showError('启用插件失败: ' + (data.message || '未知错误'));
                    }
                }
            } catch (error) {
                // 恢复开关状态
                document.getElementById(`plugin-${pluginId}`).checked = !enabled;
                showError('切换插件状态失败: ' + error.message);
            }
        }

        // 删除重复声明

        // 显示配置模态框
        async function showConfig(platformId) {
            currentPluginId = platformId;

            try {
                // 获取插件信息
                const plugin = { name: platformId };

                // 重置表单状态
                document.getElementById('plugin-config-loading').style.display = 'block';
                document.getElementById('plugin-config-error').classList.add('d-none');
                document.getElementById('plugin-config-form').innerHTML = '';

                // 创建新的模态框实例
                const modalEl = document.getElementById('plugin-config-modal');
                const oldModal = bootstrap.Modal.getInstance(modalEl);
                if (oldModal) {
                    oldModal.dispose();
                }

                const modal = new bootstrap.Modal(modalEl, {
                    backdrop: true,
                    keyboard: true
                });
                modal.show();

                // 设置标题
                document.getElementById('plugin-config-title').textContent = `${platformId} 配置文件`;

                // 获取配置文件路径
                const response = await fetch(`/api/plugin_config_file?plugin_id=${platformId}`);
                const data = await response.json();

                if (data.success && data.config_file) {
                    // 获取文件内容
                    const contentResponse = await fetch(`/api/files/read?path=${encodeURIComponent(data.config_file)}`);
                    const contentData = await contentResponse.json();

                    if (contentData.success) {
                        // 创建文本编辑器
                        const formContainer = document.getElementById('plugin-config-form');
                        formContainer.innerHTML = `
                            <div class="mb-3">
                                <textarea id="config-editor" class="form-control" style="min-height: 300px; font-family: monospace;">${contentData.content}</textarea>
                            </div>
                        `;

                        // 存储当前配置文件路径，用于保存
                        document.getElementById('plugin-config-save').setAttribute('data-config-file', data.config_file);
                        document.getElementById('plugin-config-save').textContent = '保存';

                        document.getElementById('plugin-config-loading').style.display = 'none';
                    } else {
                        throw new Error(contentData.error || '无法读取配置文件内容');
                    }
                } else {
                    throw new Error(data.error || '无法获取配置文件路径');
                }
            } catch (error) {
                console.error('加载插件配置失败:', error);

                // 显示错误
                document.getElementById('plugin-config-loading').style.display = 'none';
                const errorEl = document.getElementById('plugin-config-error');
                errorEl.classList.remove('d-none');
                errorEl.querySelector('span').textContent = error.message || '加载配置失败';
            }
        }

        // 保存配置
        document.getElementById('plugin-config-save').addEventListener('click', async function() {
            try {
                // 获取配置文件路径
                const configFile = document.getElementById('plugin-config-save').getAttribute('data-config-file');
                if (!configFile) {
                    throw new Error('未找到配置文件路径');
                }

                // 获取编辑器内容
                const content = document.getElementById('config-editor').value;

                // 显示保存中状态
                const saveBtn = document.getElementById('plugin-config-save');
                saveBtn.disabled = true;
                saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>保存中...';

                // 发送保存请求
                const response = await fetch('/api/files/write', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        path: configFile,
                        content: content
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // 显示成功提示 - 使用更现代的浮动通知
                    const successAlert = document.createElement('div');
                    successAlert.className = 'toast align-items-center text-white bg-success border-0 position-fixed top-0 start-50 translate-middle-x mt-4';
                    successAlert.style.zIndex = '9999';
                    successAlert.setAttribute('role', 'alert');
                    successAlert.setAttribute('aria-live', 'assertive');
                    successAlert.setAttribute('aria-atomic', 'true');
                    successAlert.innerHTML = `
                        <div class="d-flex">
                            <div class="toast-body">
                                <i class="bi bi-check-circle-fill me-2"></i> 配置已成功保存
                            </div>
                        </div>
                    `;
                    document.body.appendChild(successAlert);

                    // 创建Toast实例并显示
                    const toast = new bootstrap.Toast(successAlert);
                    toast.show();

                    // 关闭模态框
                    const modalEl = document.getElementById('plugin-config-modal');
                    const modalInstance = bootstrap.Modal.getInstance(modalEl);
                    modalInstance.hide();

                    // 3秒后自动关闭提示并刷新页面
                    setTimeout(() => {
                        toast.hide();
                        setTimeout(() => {
                            successAlert.remove();
                            location.reload();
                        }, 150);
                    }, 2000);
                } else {
                    throw new Error(data.error || '保存失败');
                }
            } catch (error) {
                console.error('保存配置失败:', error);
                showError(`保存配置失败: ${error.message}`);
            } finally {
                // 恢复保存按钮状态
                const saveBtn = document.getElementById('plugin-config-save');
                saveBtn.disabled = false;
                saveBtn.textContent = '保存';
            }
        });

        // 显示错误消息
        function showError(message) {
            const alert = document.createElement('div');
            alert.className = 'alert alert-danger alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3';
            alert.style.zIndex = '9999';
            alert.innerHTML = `
                <i class="bi bi-exclamation-triangle-fill me-2"></i> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="关闭"></button>
            `;

            document.body.appendChild(alert);

            // 5秒后自动关闭
            setTimeout(() => {
                alert.classList.remove('show');
                setTimeout(() => alert.remove(), 150);
            }, 5000);
        }


    </script>
{% endblock %}
